package main

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/streadway/amqp"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"log"
	"os"
	"runtime"
	"sync"
	"time"
)

var (
	config  Config
	DB      *gorm.DB
	R       sync.Mutex
	Isend   bool = false
	jishuqi int  = 0
)

type Config struct {
	Host     string
	Port     string
	User     string
	Password string
	DbName   string
}

func (conf Config) DBUrl() string {
	return fmt.Sprintf("host=%v port=%v user=%s dbname=%s password=%s sslmode=disable TimeZone=Asia/Shanghai", conf.Host, conf.Port, conf.User,
		conf.DbName, conf.Password)
}
func initDB() *gorm.DB {
	config.Host = "localhost"
	config.Port = "5432"
	config.User = "postgres"
	config.Password = "root"
	//config.DbName = "Spider"
	config.DbName = "test"
	dsn := config.DBUrl()
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Printf("连接数据库错误:%v", err)
	}
	return db
}
func Tables(db *gorm.DB) {
	err := db.AutoMigrate(
		Ips{},
	)
	if err != nil {
		fmt.Printf("register table failed,err:%v", err)
		os.Exit(0)
	}
	fmt.Print("register table success")
}

type Ips struct {
	ID         string
	IP         string
	CreateTime int64
	UpdateTime int64
	DeleteTime int64
}

func main() {
	num := runtime.NumCPU()
	runtime.GOMAXPROCS(num - 2)
	fmt.Println("Cpu 核心数量：", num)
	fmt.Printf("Info: Start\n")
	DB = initDB()
	Tables(DB)
	db, _ := DB.DB()
	defer db.Close()
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()



	forever := make(chan bool)
	for i:=1;i<6;i++{
		go func(routineNum int) {
			ch, err := conn.Channel()
			failOnError(err, "Failed to open a channel")
			defer ch.Close()
			q, err := ch.QueueDeclare(
				"ips", // name
				false,   // durable
				false,   // delete when unused
				false,   // exclusive
				false,   // no-wait
				nil,     // arguments
			)
			failOnError(err, "Failed to declare a queue")

			msgs, err := ch.Consume(
				q.Name, // queue
				"",     // consumer
				true,   // auto-ack
				false,  // exclusive
				false,  // no-local
				false,  // no-wait
				nil,    // args
			)
			failOnError(err, "Failed to register a consumer")
			for d := range msgs {
				InsertIps(d.Body)
				log.Printf("Received a message: %s", d.Body)
			}
		}(i)
	}
	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}


func InsertIps(ip []byte) {
	var ips Ips
	ips.IP = string(ip)
	ips.CreateTime = time.Now().Unix()
	id, _ := uuid.NewUUID()
	ips.ID = id.String()
	//fmt.Print(ips.IP)
	DB.Create(&ips)
	jishuqi += 1
	fmt.Println("计数器：", jishuqi)
}
// 帮助函数检测每一个amqp调用
func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}
